import { getUserInfoById, getUserProfile, login } from '@/api/user'
const state = () => {
  return {
    token: localStorage.getItem('myToken') || '',
    userInfo: {}
  }
}

const mutations = {
  // 设置token
  setToken(state, data) {
    state.token = data
    localStorage.setItem('myToken', data)
    // 存入token时间戳
    localStorage.setItem('tokenTimestamp', Date.now())
  },
  // 清除token
  removeToken(state, data) {
    state.token = ''
    localStorage.removeItem('myToken')
  },
  // 设置用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 清除用户数据
  removeUserInfo(state, data) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  async userLogin(store, data) {
    const res = await login(data)
    console.log(res)
    // 存入token
    store.commit('setToken', res)
  },
  // 获取用户基本信息
  async getUserInfo(store, data) {
    const res = await getUserProfile()
    const res2 = await getUserInfoById(res.userId)
    // console.log(res)
    console.log(res2)
    store.commit('setUserInfo', { ...res, ...res2 })
  },
  // 退出
  logout(store, data) {
    store.commit('removeUserInfo')
    store.commit('removeToken')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

